package com.xiaopangzi.websocket.directive.intercepter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 描述: 自定义WebSocket握手拦截器
 *
 * @author : sujinchen
 * @date : 2020/9/23
 */
public class MyHandshakeInterceptor implements HandshakeInterceptor {
    private Logger logger = LoggerFactory.getLogger(MyHandshakeInterceptor.class);
    /**
     * 在处理握手之前调用。
     */
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse response,
                            WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception{
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
            //生成一个UUID
            String uuid = UUID.randomUUID().toString().replace("-","");
            //将uuid放到websocketsession中
            //将uuid放到websocketsession中
            attributes.put("user_uuid", uuid);
            logger.info("beforeHandshake>>user_uuid：{}",uuid);
            HttpHeaders headers = serverHttpRequest.getHeaders();
            String origin = headers.getOrigin();
            logger.info("origin>>>"+origin);
            if (origin!=null&&origin.equals("http://localhost:63342")) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 握手完成后调用。响应状态和标题指示
     */
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                        WebSocketHandler wsHandler,  Exception exception){

    }
}
